package com.tanhua.dubbo.server.api;

import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.enums.AuditStateType;
import com.tanhua.dubbo.server.enums.CommentType;
import com.tanhua.dubbo.server.enums.TopType;
import com.tanhua.dubbo.server.pojo.Album;
import com.tanhua.dubbo.server.pojo.MsgQuery;
import com.tanhua.dubbo.server.pojo.Publish;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class MessagesApiImpl implements MessagesApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 消息通过
     *
     * @param ids
     * @return
     */
    @Override
    public String messagesPass(String[] ids) {
        String messages = updateState(ids, AuditStateType.artificiaPass);
        return messages;
    }

    /**
     * 消息拒绝
     *
     * @return
     */
    @Override
    public String messagesReject(String[] ids) {
        String messages = updateState(ids, AuditStateType.artificiaRejected);
        return messages;
    }

    /**
     * 消息撤销
     *
     * @param ids
     */
    @Override
    public String revocation(String[] ids) {
        String messages = updateState(ids, AuditStateType.artificiaNotReviewed);
        return messages;
    }

    /**
     * 总记录数
     *
     *
     * @return
     */
    @Override
    public Long queryCount(Integer page, Integer pagesize,MsgQuery msgQuery) {
        PageRequest pageRequest = PageRequest.of(page - 1, pagesize);
        String sortOrder = msgQuery.getSortOrder();
        Query query = new Query();

        //置顶优先
        query.with(Sort.by(Sort.Order.desc("topState")));

        if ("createDate".equals(msgQuery.getSortProp())){
            msgQuery.setSortProp("created");
        }
        //判断排序
        if ("ascending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.asc(msgQuery.getSortProp())));
        } else if ("descending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.desc(msgQuery.getSortProp())));
        }
        //判断状态
        if (msgQuery.getSd() != null && !("all".equals(msgQuery.getState()))) {
            query.addCriteria(Criteria.where("state").is(Convert.toInt(msgQuery.getState())));
        }


        //判断用户id
        if (msgQuery.getUid() != null) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getUid())));
        }
        //判断开始时间与结束时间
        if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
            Criteria criteria = Criteria.where("created");
            criteria.gte(msgQuery.getSd());
            if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
                criteria.lte(msgQuery.getEd());
            }
            query.addCriteria(criteria);
        }

        //判断id
        if (msgQuery.getId() != null && !("".equals(msgQuery.getId()))) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getId())));
        }

        long count = mongoTemplate.count(query.with(pageRequest), Publish.class);
        return count;
    }

    /**
     * 获取不同状态所有数量
     *
     * @return
     */
    @Override
    public Long queryStateCount(String state,MsgQuery msgQuery) {

        String sortOrder = msgQuery.getSortOrder();
        Query query = new Query();


        if ("createDate".equals(msgQuery.getSortProp())){
            msgQuery.setSortProp("created");
        }
        //判断排序
        if ("ascending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.asc(msgQuery.getSortProp())));
        } else if ("descending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.desc(msgQuery.getSortProp())));
        }
        //判断状态
        if(state != null && !("all".equals(state))) {
            query.addCriteria(Criteria.where("state").is(Convert.toInt(state)));
        }


        //判断用户id
        if (msgQuery.getUid() != null) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getUid())));
        }
        //判断开始时间与结束时间
        if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
            Criteria criteria = Criteria.where("created");
            criteria.gte(msgQuery.getSd());
            if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
                criteria.lte(msgQuery.getEd());
            }
            query.addCriteria(criteria);
        }

        //判断id
        if (msgQuery.getId() != null && !("".equals(msgQuery.getId()))) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getId())));
        }

        long count = mongoTemplate.count(query, Publish.class);
        return count;
    }

    /**
     * 消息详情
     * @param id
     * @return
     */
    @Override
    public Publish queryComment(String id) {

        Query query = Query.query(Criteria.where("id").is(id));
        Publish publish = mongoTemplate.findOne(query, Publish.class);
        return publish;

    }


    /**
     * 消息置顶
     *
     * @param id
     */
    @Override
    public String messagesTop(ObjectId id) {
        String messages = updateTop(id, TopType.Top);
        return messages;
    }

    /**
     * 消息取消置顶
     *
     * @param id
     */
    @Override
    public String messagesUntop(ObjectId id) {
        String messages = updateTop(id, TopType.NotTop);
        return messages;
    }

    /**
     * 消息翻页-
     *
     * @param page
     * @param pagesize
     * @param msgQuery
     * @return
     */
    @Override
    public List<Publish> pagePublishMessages(Integer page, Integer pagesize, MsgQuery msgQuery) {

        PageRequest pageRequest = PageRequest.of(page - 1, pagesize);
        String sortOrder = msgQuery.getSortOrder();
        Query query = new Query();

        //置顶优先
        query.with(Sort.by(Sort.Order.desc("topState")));

        if ("createDate".equals(msgQuery.getSortProp())){
            msgQuery.setSortProp("created");
        }
        //判断排序
        if ("ascending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.asc(msgQuery.getSortProp())));
        } else if ("descending".equals(sortOrder)) {
            query.with(Sort.by(Sort.Order.desc(msgQuery.getSortProp())));
        }
        //判断状态
        if (msgQuery.getSd() != null && !("all".equals(msgQuery.getState()))) {
            query.addCriteria(Criteria.where("state").is(Convert.toInt(msgQuery.getState())));
        }


        //判断用户id
        if (msgQuery.getUid() != null) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getUid())));
        }
        //判断开始时间与结束时间
        if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
            Criteria criteria = Criteria.where("created");
            criteria.gte(msgQuery.getSd());
            if (msgQuery.getSd() != null && msgQuery.getSd() != -1) {
                criteria.lte(msgQuery.getEd());
            }
            query.addCriteria(criteria);
        }

        //判断id
        if (msgQuery.getId() != null && !("".equals(msgQuery.getId()))) {
            query.addCriteria(Criteria.where("userId").is(Convert.toInt(msgQuery.getId())));
        }

        List<Publish> publishList = mongoTemplate.find(query.with(pageRequest), Publish.class);
        //判断state,topState是否为空
        publishList = checkUpdate(publishList);

        return publishList;
    }

    //判断state,topState,likeCount,CommentCount是否为空
    private List<Publish> checkUpdate(List<Publish> publishList) {
        //遍历publishList
        for (Publish publish : publishList) {
            if (publish.getTopState() == null) {
                //设置默认置顶状态
                publish.setTopState(1);
            }
            if (publish.getState() == null) {
                //设置默认状态为
                publish.setState(3);
            }
            if (publish.getLikeCount() == null) {
                //设置默认点赞数
                publish.setLikeCount(0);
            }
            if (publish.getCommentCount() == null) {
                //设置默认评论数
                publish.setCommentCount(0);
            }
            mongoTemplate.save(publish);
        }
        return publishList;
    }

    /**
     * 修改审核状态
     *
     * @param ids
     * @param artificiaPass
     * @return
     */
    @Override
    public String updateState(String[] ids, AuditStateType artificiaPass) {
        try {
            for (String id : ids) {
                Query query = Query.query(Criteria.where("id").is(id));
                Update update = Update.update("state", artificiaPass.getType());
                mongoTemplate.updateFirst(query, update, Publish.class);
            }
        } catch (Exception e) {
            return "-1";
        }
        return "1";
    }


    /**
     * 置顶状态
     *
     * @param id
     * @param topType
     * @return
     */
    public String updateTop(ObjectId id, TopType topType) {
        try {
            Query query = Query.query(Criteria.where("id").is(id));
            Update update = Update.update("topState", topType.getType());
            mongoTemplate.updateFirst(query, update, Publish.class);
        } catch (Exception e) {
            return "-1";
        }
        return "1";
    }


    /**
     * 更新点赞数
     * @param publishId
     * @param likeCount
     */
    @Override
    public void updateLikeCount(String publishId, Long likeCount) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.LIKE.getType())
        );
        Update update = Update.update("likeCount",likeCount);
        mongoTemplate.updateFirst(query, update,Publish.class);
    }

    /**
     * 更新评论数
     * @param publishId
     * @param commentCount
     */
    @Override
    public void updateCommentCount(String publishId, Long commentCount) {
        Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
                .and("commentType").is(CommentType.COMMENT.getType())
        );
        Update update = Update.update("commentCount",commentCount);
        mongoTemplate.updateFirst(query, update,Publish.class);
    }

}
